﻿using NetMQ;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace NETMQLib
{

    public class InprocClientMQ
    {
        NetMQ.Sockets.PairSocket pairSocket = null;
        int timeout = 2000;
        string url = "";
        public BaseMQModel BaseMQInfo { get; set; }
        object sendObj = new object();

        public InprocClientMQ(string title, int timeout = 2000)
        {
            BaseMQInfo = new BaseMQModel() { Title = title };
            this.timeout = timeout;
            url = $"inproc://{title}";
            pairSocket = new NetMQ.Sockets.PairSocket();
            pairSocket.Connect(url);

        }

        public string SendData(string msg)
        {
            try
            {
                lock (sendObj)
                {

                    //如果释放了就重新new
                    if (pairSocket.IsDisposed)
                    {
                        pairSocket = new NetMQ.Sockets.PairSocket();
                        pairSocket.Connect(url);
                    }
                    pairSocket.SendFrame(msg);
                    //超过固定时间则结束接收
                    bool pollResult = pairSocket.TryReceiveFrameString(TimeSpan.FromMilliseconds(timeout), out string backMsg);
                    if (!pollResult)//超时接收或者rep端关闭了，则释放连接
                    {
                        backMsg = "timeout";
                        pairSocket.Disconnect(url);
                        pairSocket.Dispose();
                    }
                    return backMsg;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void Dispose()
        {
            if (pairSocket != null && !pairSocket.IsDisposed)
            {
                pairSocket.Unbind(url);
                pairSocket.Close();
                pairSocket.Dispose();
            }
        }
    }
}
